<template>
  <div class="problem-list-container">
    <el-card class="problem-list-card">
      <template #header>
        <div class="header-container">
          <span class="header-title">题目列表</span>
          <div class="filter-container">
            <el-select v-model="selectedDifficulty" placeholder="难度" clearable @change="handleFilterChange">
              <el-option label="简单" value="0" />
              <el-option label="中等" value="1" />
              <el-option label="困难" value="2" />
            </el-select>
            <el-select v-model="selectedTag" placeholder="标签" clearable @change="handleFilterChange">
              <el-option v-for="tag in availableTags" :key="tag" :label="tag" :value="tag" />
            </el-select>
            <el-select v-model="sortBy" placeholder="排序字段" @change="handleSortChange">
              <el-option v-for="option in sortOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
            <el-select v-model="orderBy" placeholder="排序方式" @change="handleSortChange">
              <el-option v-for="option in orderOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
            <el-input
              v-model="searchTitle"
              placeholder="搜索题目"
              class="search-input"
              clearable
              @input="handleTitleSearch"
            >
              <template #prefix>
                <el-icon><el-icon-search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>
      
      <el-table
        :data="problems"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        @row-click="handleRowClick"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="title" label="标题" min-width="180">
          <template #default="{ row }">
            <span class="problem-title">{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getDifficultyType(row.difficulty)"
              size="small"
              effect="light"
            >
              {{ formatDifficulty(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tag" label="标签" min-width="150">
          <template #default="{ row }">
            <div class="tag-container">
              <el-tag
                v-for="tag in formatTags(row.tag)"
                :key="tag"
                size="small"
                effect="plain"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="统计" width="180">
          <template #default="{ row }">
            <div class="stats-container">
              <el-tooltip content="提交次数" placement="top">
                <span class="stat-item">
                  <el-icon><el-icon-upload /></el-icon>
                  {{ row.submitNum || 0 }}
                </span>
              </el-tooltip>
              <el-tooltip content="通过次数" placement="top">
                <span class="stat-item">
                  <el-icon><el-icon-check /></el-icon>
                  {{ row.passNum || 0 }}
                </span>
              </el-tooltip>
              <el-tooltip content="评论数" placement="top">
                <span class="stat-item">
                  <el-icon><el-icon-chat-dot-round /></el-icon>
                  {{ row.commentNum || 0 }}
                </span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.stop="goDetail(scope.row.id)"
              text
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '../store/user';
import { Search, Upload, Check, ChatDotRound } from '@element-plus/icons-vue';

// 图标组件
const ElIconSearch = Search;
const ElIconUpload = Upload;
const ElIconCheck = Check;
const ElIconChatDotRound = ChatDotRound;

// 路由
const router = useRouter();

// 数据状态
const problems = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 定义请求体接口
interface ProblemListRequest {
  pageNum: number;
  pageSize: number;
  sortBy: string;
  orderBy: string;
  difficulty?: string;
  tag?: string;
}

// 筛选状态
const selectedDifficulty = ref('');
const selectedTag = ref('');
const searchTitle = ref('');
const sortBy = ref('id');
const orderBy = ref('asc');

// 可用标签列表
const availableTags = ref([
  '数组', '哈希表', '字符串', '排序', '双指针', '动态规划', '贪心', '树', '链表', '图'
]);

// 排序选项
const sortOptions = [
  { label: 'ID', value: 'id' },
  { label: '评论数', value: 'comment_num' },
  { label: '提交数', value: 'submit_num' },
  { label: '通过数', value: 'pass_num' }
];

// 排序方式选项
const orderOptions = [
  { label: '升序', value: 'asc' },
  { label: '降序', value: 'desc' }
];

// 获取题目列表
const fetchProblems = async () => {
  loading.value = true;
  try {
    // 验证排序参数是否有效
    const validSortBy = ['id', 'comment_num', 'submit_num', 'pass_num'];
    const validOrderBy = ['asc', 'desc'];
    
    const currentSortBy = validSortBy.includes(sortBy.value) ? sortBy.value : 'id';
    const currentOrderBy = validOrderBy.includes(orderBy.value) ? orderBy.value : 'asc';

    // 构建请求参数
    const params = new URLSearchParams({
      pageNum: currentPage.value.toString(),
      pageSize: pageSize.value.toString(),
      sortBy: currentSortBy,
      orderBy: currentOrderBy
    });

    // 添加可选参数
    if (selectedDifficulty.value) {
      params.append('difficulty', selectedDifficulty.value);
    }
    if (selectedTag.value) {
      params.append('tag', selectedTag.value);
    }

    // 打印请求参数
    console.log('Request params:', Object.fromEntries(params.entries()));

    // 使用原生fetch发送GET请求
    const userStore = useUserStore();
    const response = await fetch(`/api/problem/list?${params.toString()}`, {
      method: 'GET',
      headers: {
        'token': userStore.token || ''
      },
      credentials: 'include'
    });

    const result = await response.json();
    
    if (result.code !== 0) {
      throw new Error(result.msg || '获取题目列表失败');
    }
    
    problems.value = result.data.records || [];
    total.value = result.data.total || 0;
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '获取题目列表失败');
    console.error('Failed to fetch problems:', error);
  } finally {
    loading.value = false;
  }
};

// 添加防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null;
  return function(this: any, ...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 使用防抖处理搜索
const debouncedTitleSearch = debounce(() => {
  if (searchTitle.value.trim()) {
    searchByTitle();
  } else {
    fetchProblems();
  }
}, 300);

// 搜索标题
const handleTitleSearch = () => {
  debouncedTitleSearch();
};

// 根据标题搜索
const searchByTitle = async () => {
  loading.value = true;
  try {
    const requestData = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchTitle.value.trim()
    };
    
    // 使用原生fetch
    const userStore = useUserStore();
    const response = await fetch('/api/problem/listByTitle', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'token': userStore.token || ''
      },
      body: JSON.stringify(requestData),
      credentials: 'include'
    });

    const result = await response.json();
    
    if (result.code !== 0) {
      throw new Error(result.msg || '搜索题目失败');
    }
    
    problems.value = result.data || [];
    total.value = Array.isArray(result.data) ? result.data.length : 0;
  } catch (error) {
    ElMessage.error('搜索题目失败');
    console.error('Failed to search problems by title:', error);
  } finally {
    loading.value = false;
  }
};

// 分页事件处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchProblems();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchProblems();
};

// 筛选变更处理
const handleFilterChange = () => {
  currentPage.value = 1;
  fetchProblems();
};

// 处理排序变化
const handleSortChange = () => {
  console.log('Sort changed:', { sortBy: sortBy.value, orderBy: orderBy.value });
  currentPage.value = 1;
  fetchProblems();
};

// 格式化难度
const formatDifficulty = (difficulty: number | string) => {
  if (difficulty === 0 || difficulty === '0') return '简单';
  if (difficulty === 1 || difficulty === '1') return '中等';
  if (difficulty === 2 || difficulty === '2') return '困难';
  return '未知';
};

// 获取难度标签类型
const getDifficultyType = (difficulty: number | string) => {
  if (difficulty === 0 || difficulty === '0') return 'success';
  if (difficulty === 1 || difficulty === '1') return 'warning';
  if (difficulty === 2 || difficulty === '2') return 'danger';
  return 'info';
};

// 格式化标签
const formatTags = (tags: string) => {
  if (!tags) return [];
  return tags.split(',').filter(tag => tag.trim());
};

// 行样式
const tableRowClassName = () => {
  return 'problem-row';
};

// 行点击事件
const handleRowClick = (row: any) => {
  goDetail(row.id);
};

// 跳转到详情页
const goDetail = (id: number) => {
  router.push(`/problem/${id}`);
};

onMounted(() => {
  fetchProblems();
});
</script>

<style scoped lang="scss">
.problem-list-container {
  padding: 20px;
  
  .problem-list-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    .header-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-title {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
      
      .filter-container {
        display: flex;
        gap: 10px;
        
        .search-input {
          width: 200px;
        }
      }
    }
    
    .problem-row {
      cursor: pointer;
      transition: background-color 0.2s;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
    
    .problem-title {
      color: #409eff;
      font-weight: 500;
    }
    
    .tag-container {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
      
      .tag-item {
        margin: 0;
      }
    }
    
    .stats-container {
      display: flex;
      gap: 15px;
      
      .stat-item {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #606266;
        font-size: 13px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>